﻿/*
 * The MIT License (MIT)
 * 
 * Copyright (c) 2012 Junhua
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 * documentation files (the "Software"), to deal in the Software without restriction, including without 
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions
 * of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 */

namespace Schedule
{
    using System;
    using System.Threading;

    public class SerialQuene : IScheduleQuene
    {
        Timer timer;

        ScheduleStack stack;

        ITask pendingTask;

        ScheduleState status;
        public ScheduleState State
        {
            get { return status; }
            set
            {
                if (status != value)
                {
                    status = value;
                    if (StateChanged != null)
                    {
                        StateChanged(this, new StateChangedArgs(status));
                    }
                }
            }
        }

        public SerialQuene()
        {
            stack = new ScheduleStack();
            timer = new Timer(OnTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
            status = ScheduleState.Ready;
        }

        public void Schedule(ITask task)
        {
            if (task == pendingTask)
            {
                return;
            }

            stack.Push(task);
            if (State == ScheduleState.Ready)
            {
                State = ScheduleState.Running;
                pendingTask = stack.Pop();
                TimerChange(task.Delay);

                if (StateChanged != null)
                {
                    StateChanged(this, new StateChangedArgs(State));
                }
            }
        }

        void OnTimerCallback(object state)
        {
            ITask task = pendingTask;
            task.Completed += OnTaskCompleted;

            try
            {
                task.Start();
            }
            catch (Exception ex)
            {
                if (Error != null)
                {
                    Error(this, new FailedEventArgs(task, ex));
                }
            }
        }

        void OnTaskCompleted(object sender, EventArgs e)
        {
            ITask task = sender as ITask;
            if (task != null)
            {
                task.Completed -= OnTaskCompleted;
            }

            GoForward();
        }

        void GoForward()
        {
            if (stack.Count > 0)
            {
                pendingTask = stack.Pop();
                TimerChange(pendingTask.Delay);
            }
            else
            {
                State = ScheduleState.Ready;
            }
        }

        void TimerChange(int pending)
        {
            timer.Change(pending, Timeout.Infinite);
        }

        public void Dispose()
        {
            timer.Dispose();
            stack.Dispose();
            pendingTask = null;
        }
        
        public event EventHandler<FailedEventArgs> Error;

        public event EventHandler<StateChangedArgs> StateChanged;
    }
}
